from django.db import models
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import User

from django_utils.request_helpers import get_ip

class UserProfileManager(models.Manager):
    def get_user_profile(self, user):
        try:
            user_profile = super(UserProfileManager, self).get(user = user)
        except ObjectDoesNotExist:
            user_profile = self.model(user = user)
            user_profile.save()
        return user_profile

class UserOpenIDManager(models.Manager):
    def get_for_openid(self, request, target_openid):
        try:
            user_openid = super(UserOpenIDManager, self).get(openid = target_openid.openid)
            user = user_openid.user
        except ObjectDoesNotExist:
            from community.utils import create_user_from_openid
            user = create_user_from_openid(request, target_openid)
        return user